/*
 * @Author: chenr 526963089@qq.com
 * @Date: 2023-03-01 11:05:20
 * @LastEditors: chenr 526963089@qq.com
 * @LastEditTime: 2023-03-01 15:14:46
 * @FilePath: /library-web/src/src-portal/hooks/useRefreshToken.ts
 * @Description: 刷新token
 */
import { watch } from 'vue';
import { storeToRefs } from 'pinia';
import { useUserStore } from '../stores/user';
import dayjs from 'dayjs';

export default () => {
  /**
   * @description: 移除刷新token
   * @return {*}
   */
  let timeInterval: any = null; // 定时器任务
  const removeRefreshToken = () => {
    clearInterval(timeInterval);
    timeInterval = null;
  };

  /**
   * @description: 定时器任务
   * @return {*}
   */
  const userStore = useUserStore();
  const _toRefreshToken = () => {
    let flag = false;
    removeRefreshToken();
    if (!userStore.access_token) return false;
    return new Promise(function (resolve, reject) {
      timeInterval = setInterval(async () => {
        const refresh_token = userStore.refresh_token;
        const timeValue = userStore.userInfo?.expires_in || 0;
        const differ = dayjs().unix() - userStore.time_stamp!;
        if (refresh_token && differ >= timeValue && !flag) {
          flag = true;
          try {
            const res = await userStore.login({
              grant_type: 'refresh_token',
              refresh_token: refresh_token,
              scope: 'all',
            });
            resolve(res);
          } catch (error) {
            reject(error);
          } finally {
            flag = false;
          }
        }
      }, 1000);
    });
  };

  /**
   * @description: 添加token刷新功能
   * @return {*}
   */
  const createRefreshToken = () => {
    const { user_id } = storeToRefs(userStore);
    watch(
      user_id!,
      () => {
        if (user_id?.value) {
          _toRefreshToken();
        } else {
          removeRefreshToken();
        }
      },
      {
        immediate: true,
      }
    );
  };

  return {
    createRefreshToken,
    removeRefreshToken,
  };
};
